//
//  WmcCloudAllPhotoVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/30.
//

import UIKit
import MJRefresh
import YPBedrock
import SVProgressHUD

// MARK: - WmcCloudAllPhotoVC + WmcVMProtocol

extension WmcCloudAllPhotoVC: WmcVMProtocol {
    typealias VMType = WmcCloudAllPhotoVM
}

// MARK: - [WmcCloudAllPhotoVC]

class WmcCloudAllPhotoVC: WmcBaseVC, WmcAlbumTransitionProtocol {
    // Lifecycle

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchData()

        WmcNotificationManager.shared.addObserver(type: .deletePhotoSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.fetchData()
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // updateUploadStatus()
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)
        title = viewModel.title
        title = "个人云相册"
        var isShowedBanner: Bool = false
        if let isShowed: Bool = WmcUserdefault.object(forKey: .State.CloudAlbum.isShowBanner) {
            isShowedBanner = isShowed
        }

        if let allPhotoDelegate = YPWmcManager.shared.uiDelegate.persionCloudAlbumAllPhotoDelegate {
            if allPhotoDelegate.navigationShowFeedback(.current) {
                makeFeedbackUI()
            }
            if allPhotoDelegate.topShowSyncBanner(.current) {
                makeDefaultUI()
            } else {
                addSubview(searchView)
                searchView.snp.makeConstraints { make in
                    make.top.equalTo(navView.snp.bottom)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(64)
                }
            }
        } else {
            makeFeedbackUI()
            makeDefaultUI()
        }

        func makeFeedbackUI() {
            navView.addSubview(contactBtn)
            contactBtn.snp.makeConstraints { make in
                make.centerY.equalTo(navView.backImageView)
                make.right.equalTo(-Wmc_standardEdge.right)
            }
        }

        func makeDefaultUI() {
            addSubview(synSettingView)
            synSettingView.snp.makeConstraints { make in
                make.top.equalTo(navView.snp.bottom)
                make.left.right.equalToSuperview()
            }

            addSubview(searchView)
            searchView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(synSettingView.snp.bottom)
                make.height.equalTo(64)
            }
        }

        addSubview(tableView)
        addSubview(badNetworkView)
        addSubview(exampleView)

        searchView.addSubview(dateView)
        searchView.addSubview(searchBtn)
        searchView.addSubview(line)

        dateView.addSubview(dateIconImageView)
        dateView.addSubview(dateLabel)
        dateView.addSubview(dateBtn)

        addSubview(emptyView)

        exampleView.addSubview(exampleImageView)
        exampleView.addSubview(takePhotoBtn)

        dateView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.centerY.equalToSuperview()
            make.height.equalTo(40)
            make.right.equalTo(searchBtn.snp.left).offset(-16)
        }

        dateIconImageView.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }

        dateLabel.snp.makeConstraints { make in
            make.left.equalTo(dateIconImageView.snp.right).offset(6)
            make.centerY.equalToSuperview()
            make.height.equalTo(20)
            make.right.equalTo(dateBtn.snp.left).offset(-10)
        }

        dateBtn.snp.makeConstraints { make in
            make.width.height.equalTo(12)
            make.right.equalTo(-12)
            make.centerY.equalToSuperview()
        }

        searchBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.width.equalTo(80)
            make.height.equalTo(36)
            make.centerY.equalToSuperview()
        }

        line.snp.makeConstraints { make in
            make.height.equalTo(1)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }

        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(searchView.snp.bottom)
        }

//        emptyView.snp.makeConstraints { make in
//            make.top.equalTo(navView.snp.bottom).offset(252)
//            make.centerX.equalToSuperview()
//        }

        emptyView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalTo(tableView)
        }

        badNetworkView.snp.makeConstraints { make in
            make.edges.equalTo(tableView)
        }

        exampleView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }

        var scale: Double = 1.0
        let exampleWidth = UIScreen.main.bounds.width
        if let image = exampleImageView.image {
            scale = image.size.height / image.size.width
        }
        let exampleHeight = exampleWidth * scale
        exampleImageView.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.right.equalToSuperview()
            make.width.equalTo(exampleWidth)
            make.height.equalTo(exampleHeight)
        }

        takePhotoBtn.snp.makeConstraints { make in
            make.top.equalTo(exampleImageView.snp.bottom).offset(45)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-50)
            make.height.equalTo(50)
        }

        view.addSubview(topButton)
        topButton.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.bottom.equalTo(-16)
            make.width.height.equalTo(60)
        }
    }

    /// <#Description#>
    override func bindViewAction() {
        contactBtn.yp.addEvent { _ in
            // 调用优化之后的h5页面
            let vm = WmcHtml5VM()
            vm.parameters = nil
            vm.questionType = .None
            vm.path = WmcHtml5VM.Html5Path.feedback
            WmcNavigatorManager.push(.html5Page, parms: vm)
        }

        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData(showLoading: false)
        })

        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadMore()
        })

        searchBtn.yp.addEvent { _ in
            WmcNavigatorManager.push(.cloudScreenPhoto)?.hidesBottomBarWhenPushed = true
        }

        dateBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self, let _ = weakSelf.viewModel.selectedDateStr else { return }
            weakSelf.dateLabel.text = "全部时间"
            weakSelf.viewModel.selectedDateStr = nil
            weakSelf.viewModel.selectedDate = nil
            weakSelf.dateBtn.setImage("triangle_bottom".wmc_image, for: .normal)
            weakSelf.dateBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            weakSelf.dateBtn.snp.updateConstraints { make in
                make.width.height.equalTo(12)
            }
            weakSelf.fetchData(showLoading: true)
        }

//        bannerCloseBtn.yp.addEvent { [weak self] _ in
//            guard let weakSelf = self else { return }
//            weakSelf.bannerView.snp.updateConstraints { make in
//                make.height.equalTo(0)
//            }
//            weakSelf.bannerView.isHidden = true
//            WmcUserdefault.save(value: true, forKey: .State.CloudAlbum.isShowBanner)
//        }

        badNetworkView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData(showLoading: true)
        }

        takePhotoBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.backAction()
        }

        NotificationCenter.default.addObserver(self, selector: #selector(photoAlbumDataDidChange(notification:)), name: NSNotification.Name(rawValue: "com.watermark.classifyAlbumDataDidChange"), object: nil)

        // 设置同步状态
        synSettingView.coverButton.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            if weakSelf.synSettingView.switchView.isOn {
                WmcTeamAlbumSynAlertView.alertView(title: "关闭后，拍摄照片/视频将无法自动同步到相册中", leftBtnTitle: "再想想", rightBtnTitle: "确认关闭", confirmB: {
                    weakSelf.viewModel.updateSynConfig(isSyn: false) { isSyn in
                        weakSelf.synSettingView.switchView.isOn = isSyn
                    }
                }).show()

            } else {
                weakSelf.viewModel.updateSynConfig(isSyn: true) { isSyn in
                    weakSelf.synSettingView.switchView.isOn = isSyn
                    weakSelf.viewModel.teamAblum?.isSync = isSyn
                }
            }
        }.disposed(by: rx.disposeBag)
    }

    override func bindViewModel() {
//        WmcUploadQueueManager.shared.startAutoUploadSubject.subscribe { [weak self] _ in
//            guard let weakSelf = self else { return }
//           // weakSelf.updateUploadStatus()
//        }.disposed(by: rx.disposeBag)
//
//        WmcUploadQueueManager.shared.completionSubject.subscribe(onNext: { [weak self] model in
//            guard let weakSelf = self else { return }
//            //weakSelf.updateUploadStatus()
//        }).disposed(by: rx.disposeBag)
//
//        WmcUploadQueueManager.shared.failureSubject.subscribe(onNext: { [weak self] model in
//            guard let weakSelf = self else { return }
//           // weakSelf.updateUploadStatus()
//        }).disposed(by: rx.disposeBag)

        let topShowHeight = (Wmc_screenHeight - Self.NavHeight - 64 - 72 - Wmc_safeAreaTop - Wmc_safeAreaBottom - 50) * 1.5
        tableView.rx.contentOffset.map { $0.y < topShowHeight }.bind(to: topButton.rx.isHidden).disposed(by: rx.disposeBag)

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        dateView.isUserInteractionEnabled = true
        dateView.addGestureRecognizer(tap)
        // 设置同步状态

        guard let album = self.viewModel.teamAblum else { return }
        self.synSettingView.configure(synStatus: album.isSync)
    }

    @objc
    func photoAlbumDataDidChange(notification: Notification) {
        fetchData(showLoading: true)
    }

    // Private

    private lazy var contactBtn: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn(title: "联系我们", image: "cloud_contact".wmc_image)
        btn.setTintColor(.wmc_mainTheme)
        btn.font = 16.wmc_font
        btn.imgSize = 20.wmc_autoHor
        return btn
    }()

//    private lazy var bannerView: UIView = {
//        let view = UIView()
//        view.backgroundColor = .wmc_grayH17_EBF2FF
//        return view
//    }()
//
//    private lazy var bannerImage: UIImageView = {
//        let imageView = UIImageView(image: "cloud_all_photo_banner".wmc_image)
//        imageView.contentMode = .scaleAspectFit
//        return imageView
//    }()
//
//    private lazy var bannerTitleLabel: UILabel = {
//        let label = UILabel()
//        label.text = "云端储存 照片永不丢失"
//        label.textColor = .wmc_grayH2_323233
//        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
//        return label
//    }()
//
//    private lazy var bannerDescLabel: UILabel = {
//        let label = UILabel()
//        label.text = "永久免费，不占手机内存"
//        label.textColor = .wmc_grayH8_8A8A99
//        label.font = UIFont.systemFont(ofSize: 14)
//        return label
//    }()
//
//    private lazy var bannerCloseBtn: UIButton = {
//        let btn = UIButton(type: .custom)
//        btn.setImage("close".wmc_image, for: .normal)
//        btn.imageEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
//        return btn
//    }()

    lazy var synSettingView: WmcCloudSynSettingView = {
        let view = WmcCloudSynSettingView()
        return view
    }()

    private lazy var searchView: UIView = {
        let view = UIView()
        return view
    }()

    private lazy var dateView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        view.layer.cornerRadius = 4
        return view
    }()

    private lazy var dateIconImageView: UIImageView = {
        let view = UIImageView(image: "cloud_calendar".wmc_image)
        return view
    }()

    private lazy var dateLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        label.text = "全部时间"
        return label
    }()

    private lazy var dateBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage("triangle_bottom".wmc_image, for: .normal)
        btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        return btn
    }()

    private lazy var searchBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage("search".wmc_image.yp.set(tintColor: UIColor.wmc_white_FFFFFF), for: .normal)
        btn.setTitle("照片", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 16.wmc_font
        btn.backgroundColor = .wmc_mainTheme
        btn.layer.cornerRadius = 4
        return btn
    }()

    private lazy var line: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.wmc_grayH15_E6E6E6
        return view
    }()

    private lazy var emptyView: WmcCloudAllPhotoEmptyView = {
        let view = WmcCloudAllPhotoEmptyView()
        view.isHidden = true
        return view
    }()

    private lazy var badNetworkView: WmcBadNetworkEmptyView = {
        let view = WmcBadNetworkEmptyView()
        view.isHidden = true
        return view
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .grouped)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcCloudAllPhotoDayCell.self, forCellReuseIdentifier: "WmcCloudAllPhotoDayCell")
        view.separatorStyle = .none
        return view
    }()

//    private lazy var uploadStatusView: WmcUploadStatusView = {
//        let view = WmcUploadStatusView()
//        view.isHidden = true
//        return view
//    }()

    private lazy var exampleImageView: UIImageView = {
        let view = UIImageView()
        view.image = "cloud_photo_example".wmc_image
        return view
    }()

    private lazy var takePhotoBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("去拍照试一下", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 18.wmc_font
        btn.setBackgroundImage(UIColor.wmc_mainTheme.yp.uiImage, for: .normal)
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        if YPWmcManager.shared.platform == .recordWork {
            btn.isHidden = true
        }
        return btn
    }()

    private lazy var exampleView: UIScrollView = {
        let view = UIScrollView()
        view.isHidden = true
        return view
    }()

    /// 置顶
    lazy var topButton: WmcNormalButton = {
        let view = WmcNormalButton()
        view.imageView.image = "teamAlbum_home_top_button".wmc_image
        view.contentEdge = .YP.Create(horizontal: 2, vertical: 2)
        view.imgSize = 60
        view.addTarget(self, action: #selector(scrollToTop), for: .touchUpInside)
        return view
    }()

    @objc
    private func tapAction() {
        SVProgressHUD.show()
        viewModel.fetchPhotoCalendarList { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.showCalendarView(dataList: list)
            SVProgressHUD.dismiss()
        } failure: { error in
            SVProgressHUD.dismiss()
            if let error = error {
                WmcHudManager.toast(error)
            } else {
                WmcHudManager.toast("网络请求失败")
            }
        }
    }

    private func showCalendarView(dataList: [WmcMediaTakePhotoDayModel]) {
        let minDate = "2020-01-01".yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)) ?? Date()
        let maxDate = WmcDateManager.shared.networkDate.value?.yp.string(.iso8601Day, identifier: .europe(.London)).yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)) ?? Date()

        let calendarSelectView = WmcCalendarSelectView(minDate: minDate, maxDate: maxDate)
        calendarSelectView.photoStatistics = dataList
        calendarSelectView.selectedDate = viewModel.selectedDate
        addSubview(calendarSelectView)

        calendarSelectView.selectedDateClosure = { [weak self] date in
            guard let weakSelf = self else { return }
            let dateStr = date.yp.string(.iso8601Day, identifier: .asia(.Shanghai))
            let displayDateStr = date.yp.string(.ymd_cn, identifier: .asia(.Shanghai))

            weakSelf.viewModel.selectedDateStr = dateStr
            weakSelf.viewModel.selectedDate = date
            weakSelf.dateLabel.text = displayDateStr
            weakSelf.dateBtn.setImage("close".wmc_image, for: .normal)
            weakSelf.dateBtn.imageEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
            weakSelf.dateBtn.snp.updateConstraints { make in
                make.width.height.equalTo(16)
            }
            weakSelf.fetchData(showLoading: true)
        }

        if let selectedDate = viewModel.selectedDate {
            calendarSelectView.scrollDate(selectedDate)
        }

        let presentVC = WmcPresentVC(config: .init(style: .sheet(),
                                                   contentView: calendarSelectView,
                                                   contentLayoutBlock: { make in
                                                       let height = 44.wmc_autoVer + 42 + 325 + Wmc_safeAreaBottom
                                                       make.left.right.bottom.equalToSuperview()
                                                       make.height.equalTo(height)
                                                   }))
        presentVC.show()
    }

    private func fetchData(showLoading: Bool = true) {
        if showLoading {
            WmcHudManager.loading()
        }

        viewModel.refresh { [weak self] list in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }

            weakSelf.tableView.reloadData()
            weakSelf.tableView.mj_header?.endRefreshing()
            if weakSelf.viewModel.hasNoMore {
                weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.tableView.mj_footer?.resetNoMoreData()
            }

            weakSelf.exampleView.isHidden = true
            weakSelf.judgeDataSourceIsEmpty()
            weakSelf.showRequestFailure(isShow: false)

            if weakSelf.viewModel.selectedDateStr == nil, list.isEmpty {
                weakSelf.tableView.isHidden = true
                weakSelf.exampleView.isHidden = false
            } else {
                weakSelf.tableView.isHidden = false
                weakSelf.exampleView.isHidden = true
            }

        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }
            weakSelf.showRequestFailure(isShow: true)
            weakSelf.tableView.mj_header?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }

    private func loadMore() {
        viewModel.loadMore { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
            if weakSelf.viewModel.hasNoMore {
                weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.tableView.mj_footer?.endRefreshing()
            }

            weakSelf.exampleView.isHidden = true
            weakSelf.judgeDataSourceIsEmpty()
        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_footer?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }

    private func showRequestFailure(isShow: Bool) {
        if viewModel.dataSource.isEmpty {
            tableView.isHidden = isShow
            badNetworkView.isHidden = !isShow
        } else {
            badNetworkView.isHidden = true
            tableView.isHidden = false
        }
    }

    private func judgeDataSourceIsEmpty() {
        emptyView.isHidden = !viewModel.dataSource.isEmpty
    }

//    private func updateUploadStatus() {
//        WmcUploadQueueV2DBManager.query { [weak self] list in
//            guard let weakSelf = self else { return }
//            var height: CGFloat = 0
//            if list.count > 0 {
//                height = 40
//                if WmcUploadQueueManager.shared.uploading {
//                    weakSelf.uploadStatusView.status = .uploading
//                } else {
//                    weakSelf.uploadStatusView.status = .failure
//                }
//            }
//            if height > 0 {
//                weakSelf.uploadStatusView.isHidden = false
//            } else {
//                weakSelf.uploadStatusView.isHidden = true
//            }
//            weakSelf.uploadStatusView.snp.updateConstraints { make in
//                make.height.equalTo(height)
//            }
//        }
//    }

    private func pushPhotoBrowser(index: Int) {
        let browseVM = WmcMediaBrowseVM()
        browseVM.topLeftStyle = .backTitle(title: "云相册")
        browseVM.albumType = .cloud
        browseVM.showIndex = index
        browseVM.mediaList = viewModel.browserDataSource
        browseVM.backStyle = .right // 从右侧返回出
        browseVM.shareFriendsCircleMode = .custom
        browseVM.shareWechatMode = .custom

        browseVM.actionBlock = { [weak self] type, index, vm in
            guard let weakSelf = self else { return }

            switch type {
            case .delete:
                vm.presentDeleteAlert { [weak self] in
                    WmcHudManager.loading()
                    weakSelf.viewModel.deleteImage(index: index) {
                        WmcHudManager.dismiss()
                        WmcHudManager.toast("删除成功")
                        WmcNotificationManager.shared.post(type: .deletePhotoSucceed, object: nil)
                        NotificationCenter.default.post(name: NSNotification.Name("com.watermark.cloudAlbumDataDidChange"), object: self, userInfo: nil)
                        browseVM.remove(at: index)

                        if weakSelf.viewModel.dataSource.isEmpty {
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                                weakSelf.fetchData(showLoading: true)
                            }
                        } else {
                            weakSelf.tableView.reloadData()
                        }
                    } failure: { error in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast("删除失败")
                    }
                }
            case .save:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    wmcImage.loadUIImage() { image in
                        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                        if photoAlbumStatus.info.isAvailable {
                            UIImageWriteToSavedPhotosAlbum(image,
                                                           weakSelf,
                                                           #selector(weakSelf.saveImage(_:didFinishSaving:contextInfo:)),
                                                           nil)
                        } else {
                            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                        }
                    }
                } else if let wmcVideo = wmcMedia as? WmcVideo { // 视频
                    switch wmcVideo.videoType {
                    case let .url(url):
                        let urlString = URL.YP.Create(url).yp.string
                        guard let keyWindow = UIApplication.shared.keyWindow else { return }
                        let progressBarView = WmcProgressBarView.showInView(keyWindow)

                        progressBarView.cancelClosure = {
                            WmcDownloadManager.shared.cancel()
                        }

                        WmcDownloadManager.shared.downloadFile(url: urlString) { value in
                            let progressText = String(format: "正在下载中%.2f", value * 100) + "%"
                            progressBarView.setProgress(Float(value), progressText: progressText)
                        } success: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("已保存到系统相册")
                        } failure: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("保存失败")
                        }

                    default: break
                    }
                }
            case .shareWechat:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .session)
                } else if wmcMedia is WmcVideo { // 视频
                    WmcHudManager.loading()
                    weakSelf.viewModel.fetchVideoShare(index: index) { r in
                        WmcHudManager.dismiss()
                        let icon = UIImage.YP.AppIcon
                        WmcShareManager.shareLink(r.url, title: r.title, description: r.content, thumbImage: icon, scene: .session)
                    } failure: { error in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast(error)
                    }
                }
            case .shareFriendsCircle:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .friendCircle)
                } else if wmcMedia is WmcVideo { // 视频
                    WmcHudManager.loading()
                    weakSelf.viewModel.fetchVideoShare(index: index) { r in
                        WmcHudManager.dismiss()
                        let icon = UIImage.YP.AppIcon
                        WmcShareManager.shareLink(r.url, title: r.title, description: r.content, thumbImage: icon, scene: .friendCircle)
                    } failure: { error in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast(error)
                    }
                }
            default: break
            }
        }
        let vc = WmcNavigatorManager.push(.imageBrowse, style: .alpha, parms: browseVM)
        vc?.hidesBottomBarWhenPushed = true
    }

    private func showShareView(_ shareAlertView: WmcShareAlertView) {
        let height = Wmc_safeAreaBottom + 214
        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: shareAlertView, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(height)
        }))
        presentVC.show()
    }

    private func shared(image: WmcImage?, scene: WmcShareManager.Scene) {
        guard let wmcImage = image else { return }
        wmcImage.loadUIImage { image in
            WmcShareManager.shareImage(image, scene: scene)
        }
    }

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("已保存到系统相册")
        }
    }
}

// MARK: UITableViewDelegate, UITableViewDataSource

extension WmcCloudAllPhotoVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return viewModel.dataSource.count
    }

    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcCloudAllPhotoDayCell = tableView.dequeueReusableCell(withIdentifier: "WmcCloudAllPhotoDayCell", for: indexPath) as! WmcCloudAllPhotoDayCell
        if let model = viewModel.dataSource.yp.object(at: indexPath.section) {
            cell.bindModel(model)
        }

        cell.clickImage = { [weak self] (model, image) in
            guard let weakSelf = self else { return }
            weakSelf.tabBarController?.tabBar.isHidden = true

            var imageModelIndex: Int?
            for (index, modelTemp) in weakSelf.viewModel.originalDataSource.enumerated() {
                if model.id == modelTemp.id {
                    imageModelIndex = index
                    break
                }
            }

            guard let imageModelIndex = imageModelIndex else {
                return
            }
            weakSelf.pushPhotoBrowser(index: imageModelIndex)
        }

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let model = viewModel.dataSource.yp.object(at: indexPath.section) {
            return model.height
        } else {
            return 0.0
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = WmcCloudAllPhotoTableHeaderView()
        if let model = viewModel.dataSource.yp.object(at: section) {
            view.bindModel(model)
        }
        return view
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 46
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = WmcCloudDateView()

        let lastDate: WmcMediaTakePhotoDayModel? = lastDate()
        view.setDate(lastDate)
        view.dateClosure = { [weak self] model in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.selectedDateStr = model.date
            weakSelf.viewModel.selectedDate = model.date.yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)) ?? Date()
            weakSelf.dateLabel.text = model.date.replacingOccurrences(of: "-", with: ".")
            weakSelf.fetchData(showLoading: true)
        }

        return view
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        let lastDate: WmcMediaTakePhotoDayModel? = lastDate()
        return lastDate != nil ? 62.0 : 0.0
    }

    private func lastDate() -> WmcMediaTakePhotoDayModel? {
        var lastDate: WmcMediaTakePhotoDayModel?
        if let date = viewModel.selectedDateStr {
            let idx = viewModel.dataCalendar.firstIndex { model in
                return date == model.date
            }
            if let idx = idx, idx > 0 {
                lastDate = viewModel.dataCalendar[idx - 1]
            }
        }
        return lastDate
    }
}

extension WmcCloudAllPhotoVC {
    /// 滑动到顶部
    @objc func scrollToTop() {
        let topRow = IndexPath(row: 0, section: 0)
        tableView.scrollToRow(at: topRow, at: .top, animated: true)
    }
}
